package com.qk.management.service.impl;

import com.qk.common.util.AliYunOSSOperators;
import com.qk.management.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@Service
public class GarbageCleanupService {

    @Autowired
    private AliYunOSSOperators ossOperators;

    @Autowired
    private UserMapper userMapper;

    public void cleanGarbageFiles() {
        // Step 1: 获取 OSS 所有文件 key
        List<String> ossKeys = ossOperators.listAllFiles();

        // Step 2: 获取数据库中有效文件 URL（如用户头像）
        Set<String> dbUrls = userMapper.selectAllFileKeys();

        // Step 3: 求差集 —— 在 OSS 中但不在数据库中的文件
        List<String> garbageFiles = ossKeys.stream()
                .filter(key -> !dbUrls.contains(key))
                .collect(Collectors.toList());

        // Step 4: 删除垃圾文件
        garbageFiles.forEach(ossOperators::deleteFile);

        log.info("共清理 {} 个垃圾文件", garbageFiles.size());
    }


}
